<template>
  <van-field
    @click="handelClick"
    :label="label"
    v-model="select.text"
    placeholder="请选择"
    is-link
    readonly
    :name="name"
    :rules="rules"
  />
  <van-field
    v-show="false"
    v-model="select.value"
    readonly
    :name="name"
  />
  <van-popup v-model:show="show" position="bottom" teleport="body">
    <van-picker
      :columns="realOptions"
      @confirm="confirm"
      @cancel="show = false"
    />
  </van-popup>
</template>

<script lang="ts">
import { defineComponent,reactive,toRefs ,watch,nextTick,PropType} from 'vue'
export default defineComponent({
  name:'tSelect',
  emits:['update:modelValue','select','change','click'],
  props:{
    modelValue: String,
    options:{
      type:Array as PropType<Record<string,any>>,
      default:[]
    },
    labelName:{
      type: String,
      default: 'label'
    },
    valueName:{
      type: String,
      default: 'value'
    },
    labelWidth:{
      type:String,
      default:'6.2rem'
    },
    rules:{
      type:Array,
      default:[]
    },
    readonly:Boolean,
    name:String,
    label:String
  },
  setup (props,{emit}) {
    const data = reactive({
      show:false,
      select:{
        text: '',
        value: props.modelValue || ''
      },
      realOptions:<Array<Record<string,any>>>[]
    })
    const update = function(list?){
      if(list){
        data.realOptions = list.map((item)=>{
          if(props.modelValue == item[props.valueName]){
            data.select.text = item[props.labelName];
          }
          return {
            text: item[props.labelName],
            value: item[props.valueName],
            data:item
          }
        })
      }else{
         data.realOptions.forEach(item=>{
            if(props.modelValue == item.value){
              data.select.text = item.text;
              data.select.value = item.value;
            }
         })
      } 
    }
    watch(()=>props.options,(data,prev)=>{
      update(data||[])
    })
    watch(()=>props.modelValue,(data,prev)=>{
      update()
    })
    nextTick(()=>{
      update(props.options);
    })
    const handelClick = ()=>{
      props.readonly?'':data.show = true
      emit('click');
    }
    return {
      ...toRefs(data),
      handelClick,
      confirm(value){
        let lastValue = data.select.value
        data.select = value;
        emit('select',data.select);
        emit('update:modelValue',data.select.value)
        if( lastValue!= value.value){
          emit('change',data.select,lastValue);
        }
        data.show = false;
      }
    }
  }
})
</script>